package com.gaoding.qa.auto.interceptor;

import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.lifecycles.MethodAnnotationLifeCycle;
import com.dtflys.forest.reflection.ForestMethod;
import com.gaoding.qa.auto.annotation.Cookie;
import com.google.common.collect.Lists;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * cookie拦截器
 * @author mobai
 * @since 2021/10/21 17:21
 */
public class CookieInterceptor implements MethodAnnotationLifeCycle<Cookie,Object> {
    @Override
    public boolean beforeExecute(ForestRequest request) {
        Method method = request.getMethod().getMethod();
        Parameter[] parameters = method.getParameters();
        if (parameters==null || parameters.length==0){
            return true;
        }
        ArrayList<String> cookies = Lists.newArrayList();
        for (int i = 0; i < parameters.length; i++) {
            if (parameters[i].isAnnotationPresent(Cookie.class)){
                val cookie=parameters[i].getAnnotation(Cookie.class);
                String argument = (String) request.getArgument(i);
                if (StringUtils.isNotBlank(argument)){
                    cookies.add(String.format("%s=%s", cookie.value(),argument));

                }
                break;
            }
        }
        if (!CollectionUtils.isEmpty(cookies)){
            request.getHeaders().addHeader("Cookie", cookies.stream().collect(Collectors.joining(";")));
        }

        return true;
    }

    @Override
    public void onMethodInitialized(ForestMethod method, Cookie annotation) {

    }
}
